﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

using ESOL.Business.Mst;
using ESOL.Business.Sales;
using ESOL.Common;
using ESOL.Common.Entity;
using ESOL.WinUI.MasterData;
using ESOL.WinUI.UICommon;
using ESOL.WinUI.Hr;
using ESOL.WinUI.Bpt;
using ESOL.WinUI.Pur;

namespace ESOL.WinUI.Sales
{
    public partial class frmMaintainSalesQuoteOrder : BaseForm.frmBaseDialogyBusinessForm
    {
        #region Variable
        public SalesQuoteOrderEntity SelectedSalesQuoteOrder { get; set; }
        private List<SalesQuoteItemEntity> DeleteList = new List<SalesQuoteItemEntity>();

        private List<SalesProdPlanApplicationItemEntity> mListApplicationItems;
        #endregion

        #region Constructor
        public frmMaintainSalesQuoteOrder()
        {
            InitializeComponent();
            if (SelectedSalesQuoteOrder == null)
            {
                SelectedSalesQuoteOrder = new SalesQuoteOrderEntity();
                SelectedSalesQuoteOrder.QuoteOrderId = Guid.NewGuid().ToString();
            }
        }

        public frmMaintainSalesQuoteOrder(List<SalesProdPlanApplicationItemEntity> list, MstCustomerEntity customer)
        {
            InitializeComponent();
            if (SelectedSalesQuoteOrder == null)
            {
                SelectedSalesQuoteOrder = new SalesQuoteOrderEntity();
                SelectedSalesQuoteOrder.QuoteOrderId = Guid.NewGuid().ToString();
            }

            SetFieldsByCustomer(customer);
            mListApplicationItems = list;
        }
        #endregion

        #region Functions
        private void SetFieldsByCustomer(MstCustomerEntity customer)
        {
            if (customer != null)
            {
                txtCustomer.Tag = customer;
                txtCustomer.Text = customer.CustomerName;
                UICommonFunctions.BindContactCombobox(cmbCustomerContact, customer.CustomerId, false);
                UICommonFunctions.BindContactGridCombobox(colCONTACT_ID, customer.CustomerId, true);
            }
            else
            {
                txtCustomer.Tag = null;
                txtCustomer.Text = "";
                UICommonFunctions.BindContactCombobox(cmbCustomerContact, "", false);
                UICommonFunctions.BindContactGridCombobox(colCONTACT_ID, "", true);
                txtCustomerContactPhone.Text = "";
            }
        }

        private void BindComboBox()
        {
            UICommon.UICommonFunctions.BindComboboxByCommonItem(cmbCurrency, "CS", false);
            UICommon.UICommonFunctions.BindComboboxByCommonItem(cmbStatus, "STATUS", false);
            UICommon.UICommonFunctions.BindComboboxByCommonItem(cmbDeliveryWay, "DW", true);
            UICommon.UICommonFunctions.BindComboboxByCommonItem(cmbPackageType, "PT", true);
            UICommon.UICommonFunctions.BindComboboxByCommonItem(cmbPaymentType, "PAYWAY", true);

            UICommon.UICommonFunctions.BindGridComboboxByCommonItem(colUNIT, "UNIT", true);
        }

        private void BindDataGridDetail()
        {
            string quoteOrderId = "";
            if (SelectedSalesQuoteOrder != null)
            {
                quoteOrderId = SelectedSalesQuoteOrder.QuoteOrderId;
            }
            DataSet ds = SalesQuoteItemBs.GetDataSetByQuoteOrderID(quoteOrderId);
            if (ds == null || ds.Tables.Count == 0)
            {
                gvMain.DataSource = null;
                return;
            }
            DataTable dt = ds.Tables[0];
            dt.AcceptChanges();
            gvMain.DataSource = dt;
            DeleteList = new List<SalesQuoteItemEntity>();
            ResetTotalAmount();
        }

        private void SetDataGridDetailByApplicationItems()
        {
            if (mListApplicationItems == null || mListApplicationItems.Count == 0)
            {
                return;
            }
            DataTable dt = (DataTable)gvMain.DataSource;
            foreach (SalesProdPlanApplicationItemEntity entity in mListApplicationItems)
            {
                DataRow dr = dt.NewRow();
                dr["QUOTE_ITEM_ID"] = Guid.NewGuid().ToString();
                dr["CONTACT_ID"] = entity.ContactId;
                dr["QUOTE_ORDER_ID"] = SelectedSalesQuoteOrder.QuoteOrderId;
                MstProductEntity product = MstProductBs.GetMstProductTypeByID(entity.ProductId);
                if (product != null)
                {
                    dr["PRODUCT_ID"] = product.ProductId;
                    dr["PRODUCT_CODE"] = product.ProductCode;
                    dr["SUGGEST_PRICE"] = product.SuggestPrice;
                }
                dr["PRODUCT_SPEC_IN"] = entity.ProductSpecIn;
                dr["PRODUCT_SPEC_OUT"] = entity.ProductSpecOut;
                dr["MATERIAL"] = entity.Material;
                dr["DIAMETER_OUT"] = entity.DiameterOut;
                dr["DIAMETER_IN"] = entity.DiameterIn;
                dr["LENGTH"] = entity.Length;
                dr["UNIT"] = entity.Unit;
                dr["QTY"] = entity.Qty;
                dr["TAX_RATE"] = 0.17;
                dr["PRICE_NO_TAX"] = decimal.Round(entity.Price, 2);
                if (cboxIsTax.Checked)
                {
                    dr["TOTAL_AMOUNT"] = decimal.Round(entity.Price * entity.Qty * (1 + CommonFunctions.ToDecimal(dr["TAX_RATE"])), 2);
                }
                else
                {
                    dr["TOTAL_AMOUNT"] = decimal.Round(entity.Price * entity.Qty, 2);
                }
                dt.Rows.Add(dr);
            }
            ResetTotalAmount();
        }

        private void ResetTotalAmount()
        {
            if (gvMain.DataSource == null)
            {
                return;
            }
            DataTable dt = gvMain.DataSource as DataTable;
            decimal totalAmount = 0;
            foreach (DataRow dr in dt.Rows)
            {
                if (string.IsNullOrEmpty(dr["TOTAL_AMOUNT"].ToString()) == false)
                {
                    decimal price = CommonFunctions.ToDecimal(dr["PRICE_NO_TAX"].ToString());
                    decimal amount = CommonFunctions.ToDecimal(dr["QTY"].ToString()) * price;
                    dr["PRICE_NO_TAX"] = price.ToString("#0.00");
                    dr["TOTAL_AMOUNT"] = amount.ToString("#0.00");
                    totalAmount += amount;
                }
            }
            totalAmount += CommonFunctions.ToDecimal(txtTransportFee.Text) + CommonFunctions.ToDecimal(txtPackageFee.Text);
            txtTotalAmount.Text = decimal.Round(totalAmount, 2).ToString();
        }

        private void ResetTax()
        {
            if (gvMain.DataSource == null)
            {
                return;
            }
            DataTable dt = gvMain.DataSource as DataTable;
            decimal totalAmount = 0;
            foreach (DataRow dr in dt.Rows)
            {
                if (dr["TOTAL_AMOUNT"] != null && CommonFunctions.IsDecimal(dr["TOTAL_AMOUNT"].ToString()))
                {
                    decimal tax = CommonFunctions.ToDecimal(dr["TAX_RATE"]) + 1;
                    decimal price = CommonFunctions.ToDecimal(dr["PRICE_NO_TAX"]);
                    if (cboxIsTax.Checked)
                    {
                        price = price * tax;
                    }
                    else
                    {
                        price = price / tax;
                    }
                    decimal amount = CommonFunctions.ToDecimal(dr["QTY"]) * price;
                    dr["PRICE_NO_TAX"] = price.ToString("#0.00");
                    dr["TOTAL_AMOUNT"] = amount.ToString("#0.00");
                    totalAmount += amount;
                }
            }
            txtTotalAmount.Text = decimal.Round(totalAmount, 2).ToString();
        }

        private void SetFields()
        {
            if (SelectedSalesQuoteOrder == null)
            {
                BindDataGridDetail();
                return;
            }
            if (string.IsNullOrEmpty(SelectedSalesQuoteOrder.SupplierId) == false)
            {
                MstSupplierEntity supplier = MstSupplierBs.GetMstSupplierById(SelectedSalesQuoteOrder.SupplierId);
                if (supplier != null)
                {
                    txtSupplier.Tag = supplier;
                    txtSupplier.Text = supplier.SupplierName;
                    UICommonFunctions.BindSupplierContactCombobox(cmbSupplierContact, supplier.SupplierId, false);
                }
            }
            if (string.IsNullOrEmpty(SelectedSalesQuoteOrder.CustomerId) == false)
            {
                MstCustomerEntity customer = MstCustomerBs.GetMstCustomerByID(SelectedSalesQuoteOrder.CustomerId);
                if (customer != null)
                {
                    SetFieldsByCustomer(customer);
                }
            }
            txtQuoteCode.Text = SelectedSalesQuoteOrder.QuoteOrderCode;
            if (string.IsNullOrEmpty(txtQuoteCode.Text))
            {
                txtQuoteCode.Text = "自动生成";
            }
            txtDeliveryCycle.Text = SelectedSalesQuoteOrder.DeliveryCycle;
            if (ThisActionType == ActionType.New)
            {
                MstPersonEntity person = MstPersonBs.GetMstPersonByID(CommonParameter.CurrentUser.PersonId);
                if (person != null)
                {
                    txtQuotePerson.Tag = person;
                    txtQuotePerson.Text = person.NameCn + " (" + person.PersonCode + ")";
                }
            }
            else
            {
                if (string.IsNullOrEmpty(SelectedSalesQuoteOrder.QuotePerson) == false)
                {
                    MstPersonEntity person = MstPersonBs.GetMstPersonByID(SelectedSalesQuoteOrder.QuotePerson);
                    if (person != null)
                    {
                        txtQuotePerson.Tag = person;
                        txtQuotePerson.Text = person.NameCn + " (" + person.PersonCode + ")";
                    }
                }
            }
            if (string.IsNullOrEmpty(SelectedSalesQuoteOrder.ContactId) == false)
            {
                cmbCustomerContact.SetSelectedValue(SelectedSalesQuoteOrder.ContactId);
            }
            txtTotalAmount.Text = SelectedSalesQuoteOrder.QuoteTotalAmount.ToString();
            cmbCurrency.SetSelectedValue(SelectedSalesQuoteOrder.Currency);
            cmbPaymentType.SetSelectedValue(SelectedSalesQuoteOrder.PaymentType);
            if (SelectedSalesQuoteOrder.IsTax == 1)
            {
                cboxIsTax.Checked = true;
            }
            else
            {
                cboxIsTax.Checked = false;
            }
            cmbDeliveryWay.SetSelectedValue(SelectedSalesQuoteOrder.TransportType);
            txtTransportFee.Text = SelectedSalesQuoteOrder.TransportFee.ToString("#0.00");
            cmbPackageType.SetSelectedValue(SelectedSalesQuoteOrder.PackageType);
            txtPackageFee.Text = SelectedSalesQuoteOrder.PackageFee.ToString("#0.00");
            dtpQuoteDate.EditValue = SelectedSalesQuoteOrder.QuoteDate;
            dtpExpiredDate.EditValue = SelectedSalesQuoteOrder.QuoteExpiredDate;
            cmbStatus.SetSelectedValue(SelectedSalesQuoteOrder.Status);
            txtAttachment.Text = SelectedSalesQuoteOrder.Attachment;
            txtRemark.Text = SelectedSalesQuoteOrder.Remark;

            UICommonFunctions.SetTextBoxDate(txtCreatedDate, SelectedSalesQuoteOrder.CreatedDate, "yyyy-MM-dd hh:mm:ss");
            UICommonFunctions.SetTextBoxPersonName(txtCreatedBy, SelectedSalesQuoteOrder.CreatedBy);
            UICommonFunctions.SetTextBoxDate(txtLastModifiedDate, SelectedSalesQuoteOrder.LastModifiedDate, "yyyy-MM-dd hh:mm:ss");
            UICommonFunctions.SetTextBoxPersonName(txtLastModifiedBy, SelectedSalesQuoteOrder.LastModifiedBy);
            UICommonFunctions.SetTextBoxDate(txtApprovedDate, SelectedSalesQuoteOrder.ApprovedDate, "yyyy-MM-dd hh:mm:ss");
            UICommonFunctions.SetTextBoxPersonName(txtApprovedBy, SelectedSalesQuoteOrder.ApprovedBy);

            BindDataGridDetail();
        }

        private void SetEntity()
        {
            if (txtSupplier.Tag != null && txtSupplier.Tag.GetType() == typeof(MstSupplierEntity))
            {
                SelectedSalesQuoteOrder.SupplierId = ((MstSupplierEntity)txtSupplier.Tag).SupplierId;
            }
            if (txtCustomer.Tag != null && txtCustomer.Tag.GetType() == typeof(MstCustomerEntity))
            {
                SelectedSalesQuoteOrder.CustomerId = ((MstCustomerEntity)txtCustomer.Tag).CustomerId;
            }
            SelectedSalesQuoteOrder.DeliveryCycle = txtDeliveryCycle.Text;
            if (txtQuotePerson.Tag != null && txtQuotePerson.Tag.GetType() == typeof(MstPersonEntity))
            {
                SelectedSalesQuoteOrder.QuotePerson = ((MstPersonEntity)txtQuotePerson.Tag).PersonId;
            }
            SelectedSalesQuoteOrder.QuoteDepartment = ((MstPersonEntity)txtQuotePerson.Tag).DepartmentId;
            if (cmbCustomerContact.SelectedValue != null && cmbCustomerContact.SelectedValue.ToString().Trim() != "")
            {
                SelectedSalesQuoteOrder.ContactId = cmbCustomerContact.SelectedValue.ToString().Trim();
            }
            SelectedSalesQuoteOrder.QuoteTotalAmount = CommonFunctions.ToDecimal(txtTotalAmount.Text);
            if (cmbCurrency.SelectedValue != null && cmbCurrency.SelectedValue.ToString().Trim() != "")
            {
                SelectedSalesQuoteOrder.Currency = cmbCurrency.SelectedValue.ToString().Trim();
            }
            if (cmbPaymentType.SelectedValue != null && cmbPaymentType.SelectedValue.ToString().Trim() != "")
            {
                SelectedSalesQuoteOrder.PaymentType = cmbPaymentType.SelectedValue.ToString().Trim();
            }
            if (cboxIsTax.Checked)
            {
                SelectedSalesQuoteOrder.IsTax = 1;
            }
            else
            {
                SelectedSalesQuoteOrder.IsTax = 0;
            }
            if (cmbDeliveryWay.SelectedValue != null && cmbDeliveryWay.SelectedValue.ToString().Trim() != "")
            {
                SelectedSalesQuoteOrder.TransportType = cmbDeliveryWay.SelectedValue.ToString().Trim();
            }
            SelectedSalesQuoteOrder.TransportFee = CommonFunctions.ToDecimal(txtTransportFee.Text);
            if (cmbPackageType.SelectedValue != null && cmbPackageType.SelectedValue.ToString().Trim() != "")
            {
                SelectedSalesQuoteOrder.PackageType = cmbPackageType.SelectedValue.ToString().Trim();
            }
            SelectedSalesQuoteOrder.PackageFee = CommonFunctions.ToDecimal(txtPackageFee.Text);
            if (dtpQuoteDate.EditValue != null)
            {
                SelectedSalesQuoteOrder.QuoteDate = Convert.ToDateTime(dtpQuoteDate.EditValue);
            }
            if (dtpExpiredDate.EditValue != null)
            {
                SelectedSalesQuoteOrder.QuoteExpiredDate = Convert.ToDateTime(dtpExpiredDate.EditValue);
            }
            SelectedSalesQuoteOrder.Status = NormalStatus.STATUS02.ToString();
            //SelectedSalesQuoteOrder.Attachment = txtAttachment.Text;
            SelectedSalesQuoteOrder.Remark = txtRemark.Text;

            if (ThisActionType == ActionType.New)
            {
                SelectedSalesQuoteOrder.CreatedDate = DateTime.Now;
                SelectedSalesQuoteOrder.CreatedBy = CommonParameter.CurrentUser.PersonId;
            }
            if (ThisActionType == ActionType.New || ThisActionType == ActionType.Modify)
            {
                SelectedSalesQuoteOrder.LastModifiedDate = DateTime.Now;
                SelectedSalesQuoteOrder.LastModifiedBy = CommonParameter.CurrentUser.PersonId;
            }
        }

        private bool CheckData()
        {
            if (string.IsNullOrEmpty(txtSupplier.Text))
            {
                MessageBox.Show("供应商不能为空！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return false;
            }
            if (string.IsNullOrEmpty(txtCustomer.Text))
            {
                MessageBox.Show("客户不能为空！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return false;
            }
            if (string.IsNullOrEmpty(txtDeliveryCycle.Text))
            {
                MessageBox.Show("交货周期不能为空！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return false;
            }
            if (string.IsNullOrEmpty(txtQuotePerson.Text))
            {
                MessageBox.Show("报价人不能为空！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return false;
            }
            if (cmbCurrency.SelectedValue == null || cmbCurrency.SelectedValue.ToString().Trim() == "")
            {
                MessageBox.Show("货币种类不能为空！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return false;
            }
            if (dtpQuoteDate.EditValue.ToString().Equals("0001/1/1 0:00:00"))
            {
                MessageBox.Show("报价日期不能为空！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return false;
            }
            if (gvMain.DataSource == null)
            {
                MessageBox.Show("报价明细不能为空！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return false;
            }
            DataTable dt = gvMain.DataSource as DataTable;
            if (dt.Rows.Count == 0)
            {
                MessageBox.Show("报价明细不能为空！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return false;
            }
            if (UICommonFunctions.CheckDataGrid(gvMain) == false)
            {
                return false;
            }
            //if (UICommonFunctions.CheckDataGrid(gvDetail) == false)
            //{
            //    return false;
            //}
            return true;
        }

        private bool Save()
        {
            try
            {
                if (CheckData() == false)
                {
                    return false;
                }
                if (ThisActionType == ActionType.New)
                {
                    SetEntity();
                    DataTable dt = (DataTable)gvMain.DataSource;
                    bool isSuccessful = SalesQuoteOrderBs.SaveQuoteOrder(true, SelectedSalesQuoteOrder, dt, DeleteList);
                    if (!isSuccessful)
                    {
                        MessageBox.Show("新增失败！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        return false;
                    }
                }
                else if (ThisActionType == ActionType.Modify)
                {
                    SetEntity();
                    DataTable dt = (DataTable)gvMain.DataSource;
                    bool isSuccessful = SalesQuoteOrderBs.SaveQuoteOrder(false, SelectedSalesQuoteOrder, dt, DeleteList);
                    if (!isSuccessful)
                    {
                        MessageBox.Show("修改失败！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        return false;
                    }
                }
                else if (ThisActionType == ActionType.Approve)
                {
                    SelectedSalesQuoteOrder.ApprovedDate = DateTime.Now;
                    SelectedSalesQuoteOrder.ApprovedBy = CommonParameter.CurrentUser.PersonId;
                    bool isSuccessful = SalesQuoteOrderBs.UpdateSalesQuoteOrder(SelectedSalesQuoteOrder);
                    if (!isSuccessful)
                    {
                        MessageBox.Show("审核失败！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        return false;
                    }
                }
                return true;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return false;
            }
        }

        private void ResetContactColumn()
        {
            if (gvMain.DataSource == null)
            {
                return;
            }
            DataTable dt = gvMain.DataSource as DataTable;
            foreach (DataRow dr in dt.Rows)
            {
                dr["CONTACT_ID"] = null;
            }
        }

        private bool UploadAttached(string fileFullName)
        {
            try
            {
                if (string.IsNullOrEmpty(fileFullName) == false)
                {
                    using (EsolWevServices.EsolService service = new EsolWevServices.EsolService())
                    {
                        SelectedSalesQuoteOrder.Attachment = SelectedSalesQuoteOrder.QuoteOrderCode + "." + CommonFunctions.GetFileExtension(fileFullName);
                        string path = service.SalesQuoteAttachedPath();
                        byte[] bytes = CommonFunctions.FileToByte(fileFullName);
                        string errMsg = "";
                        bool result = service.UploadFileNew(bytes, path + "\\" + SelectedSalesQuoteOrder.Attachment, out errMsg);
                        if (string.IsNullOrEmpty(errMsg) == false)
                        {
                            MessageBox.Show(errMsg, "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                            return false;
                        }
                        result = SalesQuoteOrderBs.UpdateSalesQuoteOrder(SelectedSalesQuoteOrder);
                        if (result)
                        {
                            txtAttachment.Text = SelectedSalesQuoteOrder.Attachment;
                        }
                        return result;
                    }
                }
                return true;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return false;
            }
        }

        private bool DownloadAttached(string fileFullName)
        {
            try
            {
                if (string.IsNullOrEmpty(fileFullName) == false)
                {
                    using (EsolWevServices.EsolService service = new EsolWevServices.EsolService())
                    {
                        string errMsg = "";
                        string path = service.SalesQuoteAttachedPath();
                        byte[] bytes = service.DownloadFileNew(path + "\\" + SelectedSalesQuoteOrder.Attachment, out errMsg);
                        if (string.IsNullOrEmpty(errMsg) == false)
                        {
                            MessageBox.Show(errMsg, "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                            return false;
                        }
                        Image image = CommonFunctions.byteArrayToImage(bytes);
                        image.Save(fileFullName);
                        image.Dispose();
                        return true;
                    }
                }
                return true;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return false;
            }
        }
        #endregion

        #region Event
        protected override void OnShown(EventArgs e)
        {
            base.OnShown(e);
            BindComboBox();
            SetFields();
            SetDataGridDetailByApplicationItems();
            if (SelectedSalesQuoteOrder != null && !string.IsNullOrEmpty(SelectedSalesQuoteOrder.Attachment))
            {
                btnDownload.Enabled = true;
            }
            else
            {
                btnDownload.Enabled = false;
            }
        }

        protected override void Click_Save()
        {
            if (Save())
            {
                this.DialogResult = DialogResult.OK;
            }
        }

        protected override void Click_SaveNew()
        {
            if (Save())
            {
                ThisActionType = ActionType.New;
                SelectedSalesQuoteOrder = new SalesQuoteOrderEntity();
                SelectedSalesQuoteOrder.QuoteOrderId = Guid.NewGuid().ToString();
                SetFields();
            }
        }

        protected override void Click_Approve()
        {
            if (SelectedSalesQuoteOrder == null)
            {
                return;
            }
            SelectedSalesQuoteOrder.Status = NormalStatus.STATUS03.ToString();
            if (Save())
            {
                this.DialogResult = DialogResult.OK;
            }
        }

        protected override void Click_Reject()
        {
            if (SelectedSalesQuoteOrder == null)
            {
                return;
            }
            SelectedSalesQuoteOrder.Status = NormalStatus.STATUS04.ToString();
            if (Save())
            {
                this.DialogResult = DialogResult.OK;
            }
        }

        private void txtQuotePerson_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            frmMaintainEmployeeQuery frm = new frmMaintainEmployeeQuery();
            if (frm.ShowDialog() == DialogResult.OK && frm.SelectedPerson != null)
            {
                txtQuotePerson.Text = frm.SelectedPerson.NameCn;
                txtQuotePerson.Tag = frm.SelectedPerson;
            }
            else
            {
                txtQuotePerson.Text = "";
                txtQuotePerson.Tag = null;
            }
        }

        private void txtSupplier_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            frmMaintainSupplierQuery frm = new frmMaintainSupplierQuery();
            if (frm.ShowDialog() == DialogResult.OK && frm.SelectedSupplier != null)
            {
                txtSupplier.Text = frm.SelectedSupplier.SupplierName;
                txtSupplier.Tag = frm.SelectedSupplier;

                UICommonFunctions.BindSupplierContactCombobox(cmbSupplierContact, frm.SelectedSupplier.SupplierId, false);
            }
            else
            {
                txtSupplier.Text = "";
                txtSupplier.Tag = null;

                UICommonFunctions.BindSupplierContactCombobox(cmbSupplierContact, "", false);
                txtSupplierContactPhone.Text = "";
            }
        }

        private void txtCustomer_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            if (txtQuotePerson.Tag == null || txtQuotePerson.Tag.GetType() != typeof(MstPersonEntity))
            {
                MessageBox.Show("请先选择业务员！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            frmMaintainCustomerQuery frm = new frmMaintainCustomerQuery((MstPersonEntity)txtQuotePerson.Tag);
            frm.ShowAllCustomer = true;
            ResetContactColumn();
            if (frm.ShowDialog() == DialogResult.OK && frm.SelectedCustomer != null)
            {
                SetFieldsByCustomer(frm.SelectedCustomer);
            }
            else
            {
                SetFieldsByCustomer(null);
            }
        }

        DataRow drItemSelected;
        private void gridView1_FocusedRowChanged(object sender, DevExpress.XtraGrid.Views.Base.FocusedRowChangedEventArgs e)
        {
            drItemSelected = gridView1.GetDataRow(e.FocusedRowHandle);
        }

        private void tsmNewLine_Click(object sender, EventArgs e)
        {
            if (gvMain.DataSource == null)
            {
                return;
            }
            DataTable dt = (DataTable)gvMain.DataSource;
            DataRow dr = dt.NewRow();
            dr["QUOTE_ITEM_ID"] = Guid.NewGuid().ToString();
            dr["QUOTE_ORDER_ID"] = SelectedSalesQuoteOrder.QuoteOrderId;
            dr["TAX_RATE"] = 0.17;
            dt.Rows.Add(dr);
        }

        private void tsmDelLine_Click(object sender, EventArgs e)
        {
            if (gvMain.DataSource == null)
            {
                return;
            }
            if (drItemSelected == null)
            {
                return;
            }
            if (drItemSelected.RowState != DataRowState.Added)
            {
                SalesQuoteItemEntity entity = new SalesQuoteItemEntity(drItemSelected);
                DeleteList.Add(entity);
            }
            DataTable dt = gvMain.DataSource as DataTable;
            dt.Rows.Remove(drItemSelected);
            ResetTotalAmount();
        }

        private void gridView1_CellValueChanged(object sender, DevExpress.XtraGrid.Views.Base.CellValueChangedEventArgs e)
        {
            if (drItemSelected == null)
            {
                return;
            }
            if (e.Column.FieldName.Equals("QTY") || e.Column.FieldName.Equals("PRICE_NO_TAX"))
            {
                decimal unitPrice = 0;
                if (string.IsNullOrEmpty(drItemSelected["PRICE_NO_TAX"].ToString()) == false)
                {
                    unitPrice += Convert.ToDecimal(drItemSelected["PRICE_NO_TAX"].ToString());
                }
                decimal qty = 0;
                if (string.IsNullOrEmpty(drItemSelected["QTY"].ToString()) == false)
                {
                    qty += Convert.ToDecimal(drItemSelected["QTY"].ToString());
                }
                drItemSelected["TOTAL_AMOUNT"] = unitPrice * qty;

                ResetTotalAmount();
            }
        }

        private void cboxIsTax_CheckedChanged(object sender, EventArgs e)
        {
            if (cboxIsTax.Checked)
            {

                gridView1.Columns["PRICE_NO_TAX"].Caption = "单价（含税）";
                gridView1.Columns["TOTAL_AMOUNT"].Caption = "小计（含税）";
                ResetTax();

            }
            else
            {

                gridView1.Columns["PRICE_NO_TAX"].Caption = "单价";
                gridView1.Columns["TOTAL_AMOUNT"].Caption = "小计";
                ResetTax();

            }
        }

        private void repositoryItemButtonEdit1_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            if (drItemSelected == null)
            {
                return;
            }
            frmMaintainProductQuery frm = new frmMaintainProductQuery();
            if (frm.ShowDialog() == DialogResult.OK && frm.SelectedProduct != null)
            {
                drItemSelected["PRODUCT_ID"] = frm.SelectedProduct.ProductId;
                drItemSelected["PRODUCT_CODE"] = frm.SelectedProduct.ProductCode;
                drItemSelected["SUGGEST_PRICE"] = frm.SelectedProduct.SuggestPrice;
                drItemSelected["PRODUCT_SPEC_IN"] = frm.SelectedProduct.ProductSpecIn;
                drItemSelected["PRODUCT_SPEC_OUT"] = frm.SelectedProduct.ProductSpecOut;
                drItemSelected["MATERIAL"] = frm.SelectedProduct.Material;
                drItemSelected["DIAMETER_OUT"] = frm.SelectedProduct.DiameterOut;
                drItemSelected["DIAMETER_IN"] = frm.SelectedProduct.DiameterIn;
                drItemSelected["LENGTH"] = frm.SelectedProduct.Length;
                drItemSelected["UNIT"] = frm.SelectedProduct.Unit;
            }
        }

        private void cmbCustomerContact_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cmbCustomerContact.SelectedItem != null)
            {
                MstCustomerContactEntity entity = (MstCustomerContactEntity)cmbCustomerContact.SelectedItem;
                if (entity != null)
                {
                    txtCustomerContactPhone.Text = entity.ContactMobilephone;
                }
            }
        }

        private void cmbSupplierContact_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cmbSupplierContact.SelectedItem != null && cmbSupplierContact.SelectedItem.GetType() == typeof(MstSupplierContactEntity))
            {
                MstSupplierContactEntity entity = (MstSupplierContactEntity)cmbSupplierContact.SelectedItem;
                if (entity != null)
                {
                    txtSupplierContactPhone.Text = entity.ContactMobilephone;
                }
            }
        }

        private void txtTransportFee_TextChanged(object sender, EventArgs e)
        {
            ResetTotalAmount();
        }

        private void txtPackageFee_TextChanged(object sender, EventArgs e)
        {
            ResetTotalAmount();
        }

        private void btnUpload_Click(object sender, EventArgs e)
        {
            if (ThisActionType == ActionType.View)
            {
                return;
            }
            if (ThisActionType == ActionType.New || SelectedSalesQuoteOrder == null)
            {
                MessageBox.Show("请先保存后再上传文件！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            OpenFileDialog fd = new OpenFileDialog();
            fd.Multiselect = false;
            fd.Filter = "JPG文件|*.jpg|PNG文件|*.png";
            if (fd.ShowDialog() == DialogResult.OK)
            {
                Cursor = Cursors.WaitCursor;
                bool result = UploadAttached(fd.FileName);
                Cursor = Cursors.Default;
                if (result)
                {
                    MessageBox.Show("上传成功！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }
        }

        private void btnDownload_Click(object sender, EventArgs e)
        {
            if (ThisActionType == ActionType.New)
            {
                MessageBox.Show("没有可下载的附件！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            if (string.IsNullOrEmpty(SelectedSalesQuoteOrder.Attachment))
            {
                MessageBox.Show("没有找到可以下载的附件！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            SaveFileDialog fd = new SaveFileDialog();
            fd.FileName = SelectedSalesQuoteOrder.Attachment;
            if (fd.ShowDialog() == DialogResult.OK)
            {
                Cursor = Cursors.WaitCursor;
                bool result = DownloadAttached(fd.FileName);
                Cursor = Cursors.Default;
                if (result)
                {
                    MessageBox.Show("下载成功！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }
        }
        #endregion

    }
}
